package com.umeox.quranplayer.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.umeox.moto.common.log.Logger
import com.umeox.quranplayer.base.BaseApp
import com.umeox.quranplayer.db.dao.ChallengeRecordDao
import com.umeox.quranplayer.db.dao.QuranAudioDao
import com.umeox.quranplayer.db.model.ChallengeRecord
import com.umeox.quranplayer.db.model.QuranAudio


/**
 * Created by Rambo 2021/8/18
 * Describe:
 */
@Database(entities = [ChallengeRecord::class, QuranAudio::class], version = 2, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {

    abstract fun challengeRecordDao(): ChallengeRecordDao

    abstract fun quranAudioDao(): QuranAudioDao


    companion object {
        private var instance: AppDatabase? = null

        /**
         * 升级数据库
         */
        val MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                Logger.i("MIGRATION_1_2")
                database.execSQL(
                    "CREATE TABLE quran_audio(id TEXT NOT NULL PRIMARY KEY, " +
                            "nameEN TEXT,nameAR TEXT,title TEXT,artist TEXT,album TEXT," +
                            "albumId INTEGER NOT NULL,coverPath TEXT,duration INTEGER NOT NULL,path TEXT,fileName TEXT,fileSize INTEGER NOT NULL)"
                )
            }
        }

        @Synchronized
        fun get(): AppDatabase {
            if (null == instance) instance = Room.databaseBuilder(
                BaseApp.getInstance().applicationContext,
                AppDatabase::class.java,
                "umeox_quran.db"
            ).addMigrations(MIGRATION_1_2)
             .allowMainThreadQueries().build()
            return instance as AppDatabase
        }
    }
}